<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\User;
use app\common\model\UserVideo;
use app\common\model\Video as ModelVideo;
use app\common\model\VideoChapter;
use app\common\model\VideoOrder;
use PDOException as GlobalPDOException;
use think\Db;
use think\db\exception\BindParamException;
use think\exception\PDOException;
use think\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\exception\DataNotFoundException;
use think\exception\HttpResponseException;
use think\Exception;
use think\Request;

/**
 * 视频课
 */
class Video extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 弹窗数据 
     * @return void
     */
    public function popup()
    {
        $data = [
            'video_pic' => config('site.video_pic'),
            'video_con' => config('site.video_con'),
        ];
        $this->success('OK', $data);
    }

    /**
     * 免费展示用户已经领取免费视频课
     * @return void
     */
    public function listVideo()
    {
        $page = $this->request->param('page', 1);
        $user_id = $this->auth->id;
        # 查询这个用户已经领取的免费视频  关联是否到期
        $video_ids = (new UserVideo())->where('buy_is', '0')->where('user_id', $user_id)->where('end_time', '>', time())->column('video_id');
        if (empty($video_ids)) {
            $this->success('OK');
        }
        $list = (new ModelVideo)->getVideoList(['video_id' => $video_ids]);
        $this->success('OK', $list);
    }


    /**
     * 免费视频课列表
     * @return void 
     */
    public function freeList()
    {
        $list = (new ModelVideo)->getVideoList(['status' => 1]);
        $this->success('OK', $list);
    }


    /**
     * 视频课详情
     * @return void
     */
    public function detail()
    {
        $user_id = $this->auth->id;
        $video_id = $this->request->param('video_id');
        $video = (new ModelVideo())->where('id', $video_id)->field('id,name,teacher_id,label,image,money,status,introduce,qrcode')->find();
        if (!$video) {
            $this->error('视频不存在');
        }
        $teacher = (new User())->where('id', $video['teacher_id'])->field('avatar,nickname')->find();
        if ($teacher) {
            $video['teacher_name'] = $teacher->nickname;
            $video['teacher_avatar'] = $teacher->avatar;
        }
        if ($video['label']) {
            $video['label'] = explode(',', $video['label']);
        } else {
            $video['label'] = [];
        }
        $video_status = $video->status;
        # 查询详情
        $video_chapter = (new VideoChapter)->getListVideoChapter($user_id, $video_id, $video_status);
        # 章节总数
        $video['video_chapter_count'] = count($video_chapter);
        # 需要购买
        if ($video_status == '2') {
            $user_video = Db::name('user_video')->where(['user_id' => $user_id, 'video_id' => $video_id, 'buy_is' => '1'])->where('end_time', '>', time())->find();
            $video['buy_is'] = !empty($user_video) ? 1 : 0; # 1已购买0=未购买
        } else {
            # 免费视频 状态直接是已购买
            $video['buy_is'] = 1;
        }
        $this->success('获取成功', [
            'video' => $video,
            'video_chapter' => $video_chapter
        ]);
    }


    /**
     * 收费视频列表
     * @return void
     */
    public function chargeList()
    {
        $list = (new ModelVideo)->getVideoList(['status' => '2'], $this->auth->id);
        $this->success('OK', $list);
    }


    public function createOrder()
    {
        $user_id = $this->auth->id;
        $video_id = $this->request->param('video_id');
        $mobile = $this->request->param('mobile');
        $info = (new ModelVideo)->where('id', $video_id)->field('id,name,money,day')->find();
        if (!$info) {
            $this->error('视频不存在');
        }
        $order = [
            'user_id' => $user_id,
            'order_sn' =>  makePaySn($user_id, 'VIDEO'),
            'video_id' => $video_id,
            'money' => $info['money'],
            'day' => $info['day'],
            'mobile' => $mobile,
            'createtime' => time(),
        ];
        $order_id = Db::name('video_order')->insertGetId($order);
        if (!$order_id) {
            $this->error("创建订单失败");
        }
        $this->success("创建订单", ['order_id' => $order_id]);
    }


    /**
     * 支付订单
     */
    public function payOrder(Request $request)
    {
        $user_id = $this->auth->id;
        $param = $request->param();
        if (!in_array($param['pay_type'], ['wechat', 'alipay'])) {
            $this->error("支付参数错误");
        }
        $order_id = $param['order_id'];
        $order = VideoOrder::get($order_id);
        if (!$order) {
            $this->error("订单不存在");
        }
        if ($order->status != '0') $this->error("订单状态错误");
        $order->order_sn =  $order_sn = makePaySn($user_id, 'VIDEO');
        $order->pay_type = $param['pay_type'] == 'test' ? 'wechat' : $param['pay_type'];
        $order->save();
        # 测试支付
        if ($param['pay_type'] == 'test') {
            $pay = (new VideoOrder())->notify_order($order_sn, 'test');
            $this->success("支付成功", compact('pay', 'order_id'));
        }
        # 正式支付
        if ($order_id) {
            $openid = '';
            if ($param['pay_type'] == 'wechat') {
                $user = new User();
                $openid = $user->where('id', $order->user_id)->value('openid');
                if (!$openid) {
                    $this->error("请先绑定微信");
                }
            }
            $params = [
                'amount' => $order->money,
                'orderid' => $order_sn,
                'type' => $param['pay_type'],
                'title' => "购买视频视课",
                'notifyurl' => $this->request->domain() . '/api/pay/notify/paytype/' . $param['pay_type'],
                'method' => 'miniapp',
                'openid' => $openid,
                'custom' => ['type' => 'set', 'id' => $order_id],
            ];
            $pay = Service::submitOrder($params);
        }
        if ($pay) {
            $this->success("支付成功", compact('pay', 'order_id'));
        } else {
            $this->error("支付失败");
        }
    }

    /**
     * 我的订单
     * @return void
     */
    public function getOrderList()
    {
        $status =  $this->request->param('status', ''); # 空 全部 0待支付 1已支付
        $list = (new VideoOrder)->getOrderList(['status' => $status], $this->auth->id);
        $this->success('OK', $list);
    }

    /**
     * 订单详情
     * @return void
     */
    public function getOrderDetail()
    {
        $order_id = $this->request->param('order_id');
        $order = VideoOrder::field('id,video_id,mobile,money,createtime,pay_time,order_sn')->where('id', $order_id)->find();
        #  查询视频课
        $video = ModelVideo::field('id,name,label,image,money,status,qrcode')->where('id', $order->video_id)->find();
        if (!$order) {
            $this->error("订单不存在");
        }
        if (!$video) {
            $this->error("视频不存在");
        }
        if ($video['label']) {
            $order['video_label'] = explode(',', $video['label']);
        } else {
            $order['video_label'] = [];
        }
        $order['video_name'] = $video['name'];
        $order['video_image'] = $video['image'];
        $order['video_qrcode'] = $video['qrcode'];
        $this->success('OK', $order);
    }
}
